package monkeytest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import source.AppLocalMySql;
import source.Common;

public class LauchTime extends Thread {
	private static String package_name = Common.PAGEKAGE;
	private static String device = new PerformanceThread().getDevicesId();
	private static String test_name = "normal";
	private static Pattern pattern_time = Pattern.compile("\\+.+?ms");
	private static Pattern pattern_name = Pattern.compile("[^.]*Activity:");
	private static boolean LauchKey = false;

	public static void main(String[] args) {
		// String timess = args[0];
		// int times = Common.getInstance().changeStringToInt(timess);
		execCmdAdb("adb logcat -c");
		Common.getInstance().sleep(1000);
		LauchTime lauchTime = new LauchTime();
		lauchTime.start();// 启动logcat统计线程
		StartApp startApp = new StartApp();// 获取startAPP实例
		for (int i = 0; i < 200; i++) {
			startApp.startJuziApp();// 启动APP
			Common.getInstance().sleep(9000);
			startApp.stopJuziApp();// 关闭APP
			Common.getInstance().sleep(5000);
		}
		lauchTime.stopLauch();// 结束统计
	}

	@Override
	public void run() {
		execCmdAdb("adb logcat -c");
		Common.getInstance().sleep(1000);
		execCmdAdb("adb logcat");
	}

	/**
	 * 停止logcat线程
	 */
	public void stopLauch() {
		LauchTime.LauchKey = true;
	}

	/**
	 * 执行adb命令
	 * 
	 * @param cmd
	 *            命令内容
	 * @param fileName
	 *            输入文件路径
	 */
	private static void execCmdAdb(String cmd) {
		System.out.println("正在执行：" + cmd);
		String OSname = System.getProperty("os.name");
		try {
			Process p = null;
			if (OSname.contains("Mac")) {
				p = Runtime.getRuntime().exec(Common.ADB_PATH + cmd);
			} else {
				p = Runtime.getRuntime().exec("cmd /c " + cmd);
			}
			// 正确输出流
			InputStream input = p.getInputStream();// 创建并实例化输入字节流
			BufferedReader reader = new BufferedReader(new InputStreamReader(input));// 先通过inputstreamreader进行流转化，在实例化bufferedreader，接收内容
			String line = "";
			while ((line = reader.readLine()) != null) {// 循环读取
				if (LauchKey) {
					p.destroy();// 结束线程
					reader.close();// 此处reader依赖于input，应先关闭
					input.close();
					return;
				}
				// 截取到log信息，分别统计两个activity的时间
				getActivityTimes(line);
			}
			reader.close();// 此处reader依赖于input，应先关闭
			input.close();
			// 错误输出流
			InputStream errorInput = p.getErrorStream();// 创建并实例化输入字节流
			BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorInput));// 先通过inputstreamreader进行流转化，在实例化bufferedreader，接收内容
			String eline = "";
			while ((eline = errorReader.readLine()) != null) {// 循环读取
				output(eline);// 输出
			}
			errorReader.close();// 此处有依赖关系，先关闭errorReader
			errorInput.close();
		} catch (

		IOException e) {
			Common.getInstance().output("执行" + cmd + "失败！");
			e.printStackTrace();
		}
	}

	/**
	 * 通过log获取activity启动用时
	 * 
	 * @param line
	 *            每条log
	 */
	public static void getActivityTimes(String line) {
		if (line.contains("Displayed") && line.contains(package_name)) {
			String activity = getActivityName(line);
			double time = getLauchTime(line);
			output(activity, time);
			AppLocalMySql.getInstance().saveLauchTime(test_name, device, package_name, activity, time);
		}
	}

	/**
	 * 获取启动时间
	 * 
	 * @param line
	 *            截取到的log信息
	 * @return 返回double时间，单位s，默认0.00
	 */
	private static double getLauchTime(String line) {
		Matcher matcher = pattern_time.matcher(line);
		if (matcher.find()) {
			line = matcher.group(0);
			line = line.substring(1, line.length() - 2);
			line = line.replace("s", ".");
			if (!line.contains(".")) {
				line = "0." + line;
			}
			double time = Common.getInstance().changeStringToDouble(line);
			return time;
		}
		return 0.00;
	}

	/**
	 * 获取activity名
	 * 
	 * @param line
	 *            截取到的log信息
	 * @return 返回activity名
	 */
	private static String getActivityName(String line) {
		Matcher matcher = pattern_name.matcher(line);
		if (matcher.find()) {
			line = matcher.group(0);
			line = line.substring(0, line.length() - 1);
		}
		return line;
	}

	public static void output(String text) {
		System.out.println(text);
	}

	public static void output(Object... object) {
		if (object.length == 1) {
			output(object[0].toString());
			return;
		}
		for (int i = 0; i < object.length; i++) {
			System.out.println("第" + (i + 1) + "个：" + object[i]);
		}
	}
}
